package com.trkj.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.jpa.CcElectornicPrescribeDAO;
import com.trkj.dao.jpa.CcHospitalElectronicDAO;
import com.trkj.dao.jpa.CcPatientDAO;
import com.trkj.dao.jpa.IJlRecipeDAO;
import com.trkj.dao.jpa.IYzrGrantMedDAO;
import com.trkj.dao.jpa.IYzrGrantMedDetDAO;
import com.trkj.dao.jpa.IYzrMedicineDAO;
import com.trkj.dao.jpa.IYzrPharStockDAO2;
import com.trkj.dao.jpa.IYzrPharmacyDAO;
import com.trkj.dao.jpa.IYzrTbstaffDAO;
import com.trkj.dao.jpa.IjlElectronicePrintDAO;
import com.trkj.dao.jpa.IjliccardDAO;
import com.trkj.pojos.CcElectornicPrescribe;
import com.trkj.pojos.CcHospitalElectronic;
import com.trkj.pojos.CcPatient;
import com.trkj.pojos.JlElectronicePrint;
import com.trkj.pojos.JlIccard;
import com.trkj.pojos.Tbstaff;
import com.trkj.pojos.YzrGrantMed;
import com.trkj.pojos.YzrGrantMedDet;
import com.trkj.pojos.YzrMedOutstock;
import com.trkj.pojos.YzrMedicine;
import com.trkj.pojos.YzrPharStock;
import com.trkj.pojos.YzrPharmacy;
import com.trkj.pojos.YzrStorehouse;
import com.trkj.vo.YzrGrantMedVo;
import com.trkj.vo.YzrMedOutstockVo;
import com.trkj.vo.YzrSaleMedicineListVo;
import com.trkj.vo.YzrSaleMedicineVo;

@Service
@Transactional
public class YzrGrantMedService {

	@Autowired
	private IYzrGrantMedDAO yzrGrantMedDAO;//药房发药
	@Autowired
	private IYzrGrantMedDetDAO yzrGrantMedDetDAO;//药房发药详情
	@Autowired
	private CcHospitalElectronicDAO ccHospitalElectronicDAO;//住院电子处方表
	@Autowired
	private CcElectornicPrescribeDAO ccElectornicPrescribeDAO;//住院电子处方详情表	
	@Autowired
	private IjlElectronicePrintDAO jlElectronicePrintDAO;//门诊处方表	
	@Autowired
	private IJlRecipeDAO jlRecipeDAO; //门诊处方详表
	@Autowired
	private CcPatientDAO ccPatientDAO;
	@Autowired
	private IjliccardDAO jliccardDAO;//card
	@Autowired
	private IYzrPharStockDAO2 yzrPharStockDAO2;//药房库存
	@Autowired
	private IYzrMedicineDAO yzrMedicineDAO;
	@Autowired
	private IYzrTbstaffDAO yzrTbstaffDAO;
	@Autowired
	private IYzrPharmacyDAO yzrPharmacyDAO;
	
	/**
	 * 根据id查询发药详情
	 * @param grantMedId
	 * @return
	 */
	public List<YzrGrantMedDet> queryDetByGrantId(String grantMedId){
		return yzrGrantMedDetDAO.findDetByGrantId(grantMedId);
	}
	
	
	/*
	 * 根据id查询发药信息
	 */
	public YzrGrantMedVo queryGrantById(String grantMedId){
		return outstockPoToVo(yzrGrantMedDAO.findOne(grantMedId));
	}
	
	
	/**
	 * 分页查询发药信息
	 * @param page
	 * @param rows
	 * @return
	 */
	public Map<String,Object> queryAllGrantstock(int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrGrantMed> list = yzrGrantMedDAO.findAllGrant(pr);
		long total = yzrGrantMedDAO.count();
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", grantListToVo(list));
		return map;
	}
	private List<YzrGrantMedVo> grantListToVo(List<YzrGrantMed> list){
		if(list == null) return null;
		List<YzrGrantMedVo> listVo = new ArrayList<>();
		
		for(YzrGrantMed purchOrder: list){
			YzrGrantMedVo purchOrderVo = outstockPoToVo(purchOrder);
			listVo.add(purchOrderVo);
		}
		return listVo;
	}
	public YzrGrantMedVo outstockPoToVo(YzrGrantMed purchOrder){
		YzrGrantMedVo purchOrderVo = new YzrGrantMedVo();
		purchOrderVo.setGrantMedId(purchOrder.getGrantMedId());
		purchOrderVo.setGrantMedKind(purchOrder.getGrantMedKind());
		purchOrderVo.setGrantMedPharmacyId(purchOrder.getGrantMedPharmacyId());
		purchOrderVo.setGrantMedChufangId(purchOrder.getGrantMedChufangId());
		purchOrderVo.setGrantMedBingrenName(purchOrder.getGrantMedBingrenName());
		purchOrderVo.setGrantMedCaozuoyuan(purchOrder.getGrantMedCaozuoyuan());
		purchOrderVo.setGrantMedDate(purchOrder.getGrantMedDate());
		purchOrderVo.setGrantMedMoney(purchOrder.getGrantMedMoney());
		
		BigDecimal rkr = purchOrder.getGrantMedCaozuoyuan();
		String phar2 = purchOrder.getGrantMedPharmacyId();
		
		if(rkr != null){
			Tbstaff staff = yzrTbstaffDAO.findOne(rkr.longValue());
			purchOrderVo.setStaffName(staff!=null? staff.getStaffName():null);
		}
		
		if(phar2 != null){		
			YzrPharmacy phar = yzrPharmacyDAO.findOne(phar2);	
			purchOrderVo.setPharName(phar != null ? phar.getPharmacyName() : null);
		}

		return purchOrderVo;
	}
	
	
	
	
	
	/**
	 * 提交拿药数据
	 * @param medList
	 * @param staffId
	 * @param yaofangkind
	 * @param yf
	 * @param zje
	 * @param chufangId
	 * @param br
	 */
	public String addGrant(YzrSaleMedicineListVo medList,Long staffId,String yaofangkind,String yf,String zje,long chufangId,String br){
		
		String result = "";
		
		// 获取年份
		String year = getNowDate();
		//拼接
		String name = "FY-" + year;	
		String nameDet = "FD-" + year;
		String n = yzrGrantMedDAO.findId(name);
		System.out.println("从数据库中读取的最大采购编号："+n);
		//发药编号，发药日期，发药类型（门诊/药房），药房，操作员，总金额/处方、病人姓名
		YzrEntityService entityService = new YzrEntityService();
		String purId = entityService.getId(name, n);
		YzrGrantMed grantMed = new YzrGrantMed();
		grantMed.setGrantMedId(purId);
		grantMed.setGrantMedDate(new Date());
		grantMed.setGrantMedKind(yaofangkind);
		grantMed.setGrantMedPharmacyId(yf);
		grantMed.setGrantMedCaozuoyuan(new BigDecimal(staffId));
		grantMed.setGrantMedMoney(new BigDecimal(zje));
		grantMed.setGrantMedChufangId(new BigDecimal(chufangId));
		grantMed.setGrantMedBingrenName(br);
		yzrGrantMedDAO.save(grantMed);		
		
		for(YzrSaleMedicineVo med: medList.getMedList()){
			//找到库存数量
			String medId = med.getMedId();
			String pihao = med.getPihao();
			YzrPharStock stock = yzrPharStockDAO2.findByMedicine(medId, pihao);
			if(stock != null){
				//判断数量是否大于库存数量
				if((stock.getPharStockMedNumber().compareTo(med.getNumber())) ==1 ){
					
					//发药详情单号，发药编号，药品名称，批号，单位，规格，单价（卖出价格），数量，金额，备注
					YzrGrantMedDet medDet = new YzrGrantMedDet();
					String nDet = yzrGrantMedDetDAO.findId(nameDet);
					medDet.setGrantMedDetId(entityService.getId(nameDet, nDet));
					medDet.setGrantMedDetGrantMedId(purId);
					medDet.setGrantMedDetMedId(med.getMedId());
					medDet.setGrantMedDetMedName(med.getMedName());
					medDet.setGrantMedDetBatchnumber(med.getPihao());
					medDet.setGrantMedDetPrice(med.getSalePrice());
					medDet.setGrantMedDetMoney(med.getMoney());
					medDet.setGrantMedDetNumber(med.getNumber());
					yzrGrantMedDetDAO.save(medDet);
					
					
					//找到药品，减少库存
					stock.setPharStockMedNumber(stock.getPharStockMedNumber().subtract(med.getNumber()));
					yzrPharStockDAO2.save(stock);
				}else{
					result=med.getMedName()+"库存不足";
				}
			}			
			
		}
		//修改拿药状态
		CcHospitalElectronic cc = ccHospitalElectronicDAO.findOne(chufangId);
		cc.setHospeleRemarks("已完成");
		ccHospitalElectronicDAO.save(cc);
		
		
		return result;
	}
	
	
	
	
	/**
	 * 住院处方单
	 * @return
	 */
	public List<CcHospitalElectronic> queryByNoSuccess(){
		List<CcHospitalElectronic> list = ccHospitalElectronicDAO.findByNoSuccess();
		return list;
	}	
	/**
	 * 根据处方号找到住院id,然后再找到病人名字
	 * 
	 */
	public String findBingRenName(long chufangId){
		CcHospitalElectronic cf = ccHospitalElectronicDAO.findOne(chufangId);
		BigDecimal zhuyuanId = cf.getHeSickid();
		long zhuyuanId2 = zhuyuanId.longValue();
		CcPatient patient = ccPatientDAO.findOne(zhuyuanId2);
		return patient.getPname();
	}
	
	/**
	 * 根据住院处方id找到下面所有的药品
	 * 根据药品id找到批号
	 */
	public List<YzrSaleMedicineVo> queryAllMedDet(BigDecimal chufangId){
		
		//根据处方id找到处方药品详情
		List<CcElectornicPrescribe> list = ccElectornicPrescribeDAO.findAllMedDet(chufangId);
		
		List<YzrSaleMedicineVo> pihaolist= new ArrayList<YzrSaleMedicineVo>();
		
		for(CcElectornicPrescribe c:list){
			
			//根据药品id，找药品批号
			List<YzrPharStock> pharList = yzrPharStockDAO2.findPiHaoByMedId(c.getDrugId());	
			for(YzrPharStock stock:pharList){
				BigDecimal shuliang = stock.getPharStockMedNumber();
				BigDecimal b = new BigDecimal("0");
				int temp = shuliang.compareTo(b);
				YzrSaleMedicineVo med = new YzrSaleMedicineVo();
				if(temp == 1){
					System.err.println("进行赋值");
					med.setPihao(stock.getPharStockBatchnumber());//批号
					med.setMedId(c.getDrugId());//药品id
					YzrMedicine medicine = yzrMedicineDAO.findOne(c.getDrugId());
					med.setMedName(medicine.getMedName());//名称
					med.setNumber(c.getEpAmount());//数量
					med.setMoney(stock.getPharStockPrice().multiply(c.getEpAmount()));//金额
					med.setSalePrice(stock.getPharStockPrice());//单价
					med.setStockNumber(stock.getPharStockMedNumber());//库存数量
					pihaolist.add(med);
					break;
				}else{
					System.err.println("药品不足！");
				}
			}
		}
		System.err.println("发药详情："+pihaolist.size());
		
		return pihaolist;
	}
	
	
	
	
	/**
	 * 格式化日期
	 * @return
	 */
	public static String getNowDate() {
		  Date currentTime = new Date();
		  SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		  String dateString = formatter.format(currentTime);
		  return dateString;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * 门诊处方单
	 * @return
	 */
	/*public List<JlElectronicePrint> findByNoSucessMZ(){
		return jlElectronicePrintDAO.findByNoSucess();
	}
	
	
	*//**
	 * 根据门诊处方id找到卡号，然后获取病人姓名
	 *//*
	public String queryBRMenZhen(long chufangId){
		JlElectronicePrint mz = jlElectronicePrintDAO.findOne(chufangId);
		BigDecimal idcard = mz.getIerId();
		long idcard2 = idcard.longValue();
		JlIccard card = jliccardDAO.findOne(idcard2);
		return card.getIName();
	}*/
	
	/**
	 * 根据门诊处方编号，查找详情
	 */
	
	//state是状态
	
	//根据处方表找到病人姓名和药品信息
	
	//可以修改数量
	//根据药品查找出库存的数量
}
